// ***************************************************************
// Copyright (c) Axeda Corporation. All rights reserved
// ***************************************************************


package com.davidjmcclelland.common;

//import com.axeda.util.SeleniumConfigReader;
//import com.axeda.util.SeleniumConfiguration;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
//import java.util.concurrent.TimeUnit;

import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.Selenium;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;


/**
 * SeleniumWebdriverTest
 * <Class description>
 *
 * @version $
 *          <p/>
 *          Created on 1/8/13
 */

public class SeTestBase extends SeleneseTestBase
{
    protected static Selenium selenium;
    protected static WebDriver driver;
    //protected SeleniumConfiguration configuration;
    protected String baseUrl;
    public String parentWindowHandle;
    protected static final String FIREFOX = "Firefox";
    protected static final String IE = "IE";
    protected static final String CHROME = "Chrome";
    protected static final String SAFARI = "Safari";
    private final Logger logger = Logger.getLogger(SeTestBase.class);
    //protected LoginPage loginPage = null;
    //protected MenuNavigationPage menuNavigationPage = null;

    public void setUp() throws Exception
    {
       logger.info("Setup class: " + this.getClass().getName());
        //driver = new FirefoxDriver();
        driver = new ChromeDriver();
 /*        if ((configuration = getConfigurationEnvParams()) == null)
        {
            SeleniumConfigReader reader = new SeleniumConfigReader();
            configuration = reader.getSeleniumConfiguration();
        }
        createDriver();
        menuNavigationPage = new MenuNavigationPage(driver, selenium, configuration);
        loginPage = new LoginPage(driver, selenium, configuration);
        loginPage.loginUser();
        */
    }

    public void tearDown() throws Exception
    {
        Assert.assertNotNull(driver, "Driver was null before we got to SeleniumWebdriverTestBase.tearDown()");
        //loginPage.logoutUser();
        super.tearDown();
        try
        {
            driver.quit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        driver = null;
        //selenium.stop();
        //selenium = null;
        logger.debug("Tore down class: " + this.getClass().getName());
    }

/*    private SeleniumConfiguration getConfigurationEnvParams()
    {
        Properties properties = new Properties();
        if (System.getProperty(SeleniumConfiguration.DEPLOYHOST_NAME) != null)
        {
            properties.setProperty(SeleniumConfiguration.DEPLOYHOST_NAME, System.getProperty(SeleniumConfiguration.DEPLOYHOST_NAME));
        }
        if (System.getProperty(SeleniumConfiguration.DEPLOYHOST_PORT) != null)
        {
            properties.setProperty(SeleniumConfiguration.DEPLOYHOST_PORT, System.getProperty(SeleniumConfiguration.DEPLOYHOST_PORT));
        }
        if (System.getProperty(SeleniumConfiguration.SELENIUM_HOST) != null)
        {
            properties.setProperty(SeleniumConfiguration.SELENIUM_HOST, System.getProperty(SeleniumConfiguration.SELENIUM_HOST));
        }
        if (System.getProperty(SeleniumConfiguration.SELENIUM_PORT) != null)
        {
            properties.setProperty(SeleniumConfiguration.SELENIUM_PORT, System.getProperty(SeleniumConfiguration.SELENIUM_PORT));
        }
        if (System.getProperty(SeleniumConfiguration.BROWSER_NAME) != null)
        {
            properties.setProperty(SeleniumConfiguration.BROWSER_NAME, System.getProperty(SeleniumConfiguration.BROWSER_NAME));
        }
        if (System.getProperty(SeleniumConfiguration.BROWSER_PLATFORM) != null)
        {
            properties.setProperty(SeleniumConfiguration.BROWSER_PLATFORM, System.getProperty(SeleniumConfiguration.BROWSER_PLATFORM));
        }
        if (System.getProperty(SeleniumConfiguration.BROWSER_VERSION) != null)
        {
            properties.setProperty(SeleniumConfiguration.BROWSER_VERSION, System.getProperty(SeleniumConfiguration.BROWSER_VERSION));
        }
        if (System.getProperty(SeleniumConfiguration.LOGIN_NAME) != null)
        {
            properties.setProperty(SeleniumConfiguration.LOGIN_NAME, System.getProperty(SeleniumConfiguration.LOGIN_NAME));
        }
        if (System.getProperty(SeleniumConfiguration.LOGIN_PASSWORD) != null)
        {
            properties.setProperty(SeleniumConfiguration.LOGIN_PASSWORD, System.getProperty(SeleniumConfiguration.LOGIN_PASSWORD));
        }
        if (System.getProperty(SeleniumConfiguration.LOGIN_SSL) != null)
        {
            properties.setProperty(SeleniumConfiguration.LOGIN_SSL, System.getProperty(SeleniumConfiguration.LOGIN_SSL));
        }

        if (properties.size() > 0)
        {
            return new SeleniumConfiguration(properties);
        }
        else
        {
            return null;
        }
    }
*/
/*
    private void createDriver() throws MalformedURLException
    {
        DesiredCapabilities capabilities = null;
        if (driver != null && selenium != null)
        {
            return;
        }
        if (FIREFOX.equals(configuration.getBrowser()))
        {
            capabilities = DesiredCapabilities.firefox();
            driver = new RemoteWebDriver(new URL(configuration.getSeleniumUrl()), capabilities);
        }
        else if (IE.equals(configuration.getBrowser()))
        {
            capabilities = DesiredCapabilities.internetExplorer();
            driver = new RemoteWebDriver(new URL(configuration.getSeleniumUrl()), capabilities);
        }
        else if (CHROME.equals(configuration.getBrowser()))
        {
            capabilities = DesiredCapabilities.chrome();
            driver = new RemoteWebDriver(new URL(configuration.getSeleniumUrl()), capabilities);
        }
        else if (SAFARI.equals(configuration.getBrowser()))
        {
            capabilities = DesiredCapabilities.safari();
            driver = new RemoteWebDriver(new URL(configuration.getSeleniumUrl()), capabilities);
        }
        driver.manage().window().setPosition(new Point(0, 0));
        driver.manage().window().setSize(new Dimension(1920, 1080));


        baseUrl = configuration.getBaseUrl();

        // Create the Selenium implementation
        capabilities.setBrowserName(configuration.getBrowser());
        capabilities.setPlatform(configuration.getBrowserPlatform());
        capabilities.setVersion(configuration.getBrowserVersion());

        selenium = new WebDriverBackedSelenium(driver, configuration.getBaseUrl());
        selenium.deleteAllVisibleCookies();
        selenium.deleteCookie("", "");
        parentWindowHandle = driver.getWindowHandle();
    }
*/
    /**
     * Wait for an element to display, the total number of seconds to wait is defined in the user.properties file; wait.time.ms
     *
     * @param id
     * @return
     */
    public static WebElement findElementById(WebDriver driver, String id, long iterations)
    {
        WebElement element = null;
        for (int i = 0; i < iterations; i++)
        {
            try
            {
                element = driver.findElement(By.id(id));
                if(element != null && element.isDisplayed())
                {
                    return element;
                }
            }
            catch (Exception ex)
            {
                try
                {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e){}
            }
        }
        return element;
    }

    /**
     * Wait a configurable amount of seconds to determine whether an element is present on the page.
     *
     * @param element String containing the element name.
     * @return a boolean indicating whether the element was found or not.
     */
    /*
    protected boolean isElementPresent(String element)
    {
        int t = 0;
        while (!(selenium.isElementPresent(element)) && t < configuration.getTimeout())
        {
            try
            {
                Thread.sleep(1000);
                t++;
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        return t < configuration.getTimeout() ? true : false;
    }
*/
    /**
     * Wait a configurable amount of seconds to determine whether a CSS element is present on the page.
     *
     * @param element String containing the element name.
     * @return a boolean indicating whether the element was found or not.
     */
    public static WebElement isElementPresentByCss(WebDriver driver, String element, long iterations)
    {
        List<WebElement> elements = null;

        for (int i = 0; i < iterations; i++)
        {
            try
            {
                elements = driver.findElements(By.cssSelector(element));
            }
            catch (Exception ex)
            {
                try
                {
                    Thread.sleep(500);
                }
                catch (InterruptedException e){}
            }
            if(elements != null && elements.size() > 0)
            {
                return elements.get(0);
            }
            else
            {
                try
                {
                    Thread.sleep(500);
                }
                catch (InterruptedException e){}
            }
        }
        return null;
    }



    /**
     * Wait a configurable amount of seconds to determine whether an element is present on the page. It will refresh
     * the page each time by clicking on the 'Refresh' icon.
     *
     * @param
     * @return a boolean indicating whether the element was found or not.
     */
 /*   protected boolean isTextPresent(String element)
    {
        int t = 0;
        while (!(selenium.isTextPresent(element)) && t < configuration.getTimeout())
        {
            try
            {
                Thread.sleep(1000);
                driver.findElement(By.cssSelector("img[alt=\"Refresh\"]")).click();
                t++;
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        return t < configuration.getTimeout() ? true : false;
    }
*/
    public List<String> recentAssetsPodList(int iFrameID)
    {
        driver.findElement(By.id("LogoArea")).click();
        selenium.waitForPageToLoad("30000");
        List<String> assetList = new ArrayList<String>();
        driver.switchTo().frame("iFrame_" + iFrameID);
        List<WebElement> recentAssets = driver.findElements(By.cssSelector("[id='assetName']"));
        for (WebElement assetName : recentAssets)
        {
//      assetList.add(assetName.getText());
//      The next line gets the asset name
            assetList.add(assetName.findElement(By.cssSelector("[id='link']")).getText());
//      To get location use the above line w/ Selector class=location
        }
        driver.switchTo().defaultContent();
        return assetList;
    }
/*
    protected void goInFrame(String newContext)
    {
        if (newContext.contains("iFrame"))
        {
            logger.debug("switching to iFrame context");
            driver.findElement(By.id("LogoArea")).click();
            selenium.waitForPageToLoad(MenuNavigationPage.PAGE_LOAD_TIMEOUT);
            driver.switchTo().frame(newContext);
        }
    }
    */
}
